package com.middleware.server.impl;


import com.middleware.config.CustomException;
import com.middleware.redis.RedisScriptTemplate;
import com.middleware.server.RedisLuaServer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * redis lua  业务实现
 *
 * @author Mr.Zhong
 * @description
 * @date 2022/04/20 14:51
 */
@Service
public class RedisLuaServerImpl implements RedisLuaServer {


    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 根据手机号限制请求次数
     *
     * @param mobileNo 手机号
     * @param time     间隔时间/秒,1为一秒内只能请求一次
     * @return Boolean
     */
    @Override
    public Boolean mobileArmor(String mobileNo, int time) {
        if (StringUtils.isEmpty(mobileNo) || time < 1) {
            throw new CustomException("参数异常！", 402);
        }
        List<String> list = new ArrayList<>();
        list.add(mobileNo);
        Boolean bl = false;
        try {
            bl = (Boolean) redisTemplate.execute(RedisScriptTemplate.MOBILE_ARMOR_EXPIRE_SCRIPT, list, time);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bl;
    }

    /**
     * redis lua实现秒杀扣减库存业务
     *
     * @param activityId 活动编号或ID
     * @param amount     扣减库存数
     * @return
     */
    @Override
    public Long seckill(String activityId, int amount) {
        if (StringUtils.isEmpty(activityId) || amount < 1) {
            throw new CustomException("参数异常！", 402);
        }
        List<String> list = new ArrayList<>();
        list.add(activityId);
        Long bl = null;
        try {
            bl = (Long) redisTemplate.execute(RedisScriptTemplate.ACTIVITY_NUMBER_SECKILL, list, amount);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bl;
    }


}
